package udp;


import java.net.InetSocketAddress;
import java.util.Scanner;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

/**
 * UDP Client
 *
 * @author 胡海龙
 *
 */
public class UdpClient {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpClientHandler());
            Channel channel = b.bind(8081).sync().channel();
            Scanner sc = new Scanner(System.in);
            while (sc.hasNext()) {
                String sendMessage = sc.next();
                if ("quit".equals(sendMessage)) {
                    break;
                }
                // 像网段内的所有广播机广播UDP消息
                channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(sendMessage, CharsetUtil.UTF_8),
                        new InetSocketAddress("255.255.255.255", 8080)));
            }
            sc.close();
            channel.close();
        } finally {
            group.shutdownGracefully();
        }
    }
}

